Link to this headingpostMessage

A secure way to enable communication between two windows (or tabs) that belong to different origins (domains). Can pass JSON data oneway between origin1 and origin2

Link to this headingBasic Example

Open a new window and send a message to the other origin

origin1.html:

<!DOCTYPE html> <html> <head> <title>Origin 1</title> </head> <body> <button onclick="sendMessage()">Send Message</button> <script> function sendMessage() { const otherWindow = window.open('https://origin2.com/origin2.html'); const message = 'Hello from Origin 1!'; const targetOrigin = 'https://origin2.com'; otherWindow.postMessage(message, targetOrigin); } </script> </body> </html>

origin2.html:

<!DOCTYPE html> <html> <head> <title>Origin 2</title> </head> <body> <script> window.addEventListener('message', receiveMessage, false); function receiveMessage(event) { if (event.origin === 'https://origin1.com') { alert('Received message: ' + event.data); } } </script> </body> </html>

Link to this headingIFrame Example

Parent.html:

<!DOCTYPE html> <html> <head> <title>Parent Window</title> </head> <body> <iframe src="https://origin2.com/child.html"></iframe> </body> </html>

Parent.html:

<!DOCTYPE html> <html> <head> <title>Child Window</title> </head> <body> <button onclick="sendMessage()">Send Message to Parent</button> <script> function sendMessage() { const message = 'Hello from Child Window!'; parent.postMessage(message, 'https://origin1.com'); } </script> </body> </html>

Link to this headingSecurity

https://book.hacktricks.xyz/pentesting-web/postmessage-vulnerabilities